package com.imooc.miaosha.service;

import com.google.common.collect.Maps;
import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.rabbitmq.MQSender;
import com.imooc.miaosha.rabbitmq.MiaoshaMessage;
import com.imooc.miaosha.redis.AccessKey;
import com.imooc.miaosha.redis.GoodsKey;
import com.imooc.miaosha.redis.MiaoshaKey;
import com.imooc.miaosha.result.Const;
import com.imooc.miaosha.result.Result;
import com.imooc.miaosha.util.MD5Util;
import com.imooc.miaosha.vo.MiaoshaGoodsVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.domain.OrderInfo;
import org.springframework.web.bind.annotation.RequestParam;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.security.auth.login.Configuration;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class MiaoshaService implements InitializingBean {

    private final GoodsService goodsService;

    private final OrderService orderService;
    private final RedisService redisService;
    private final MQSender mqSender;
    private HashMap<Long, Boolean> localMap = Maps.newHashMap();

    @Autowired
    public MiaoshaService(GoodsService goodsService, OrderService orderService, RedisService redisService, MQSender mqSender) {
        this.goodsService = goodsService;
        this.orderService = orderService;
        this.redisService = redisService;
        this.mqSender = mqSender;
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderInfo miaosha(MiaoshaUser user, long goodsId) {

        MiaoshaGoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        boolean flag = goodsService.reduceStock(goods);
        //减库存成功了再生成订单
        if (flag) {
            return orderService.createOrder(user, goods);
        }
        //如果减库存失败说明秒完了,存一个卖完标记
        setGoodsOver(goodsId);
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        List<MiaoshaGoodsVo> list = goodsService.listGoodsVo();
        if (list == null) {
            return;
        }
        //初始化时将商品库存加载到缓存中
        for (MiaoshaGoodsVo miaoshaGoodsVo : list) {
            redisService.set(GoodsKey.goodsStock,
                    "" + miaoshaGoodsVo.getId(), miaoshaGoodsVo.getStockCount());
            localMap.put(miaoshaGoodsVo.getId(), false);
        }
    }

    public BufferedImage createVerifyCode(MiaoshaUser user, long goodsId) {
        if (user == null || goodsId <= 0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisService.set(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, rnd);
        //输出图片
        return image;
    }


    public Result<Integer> getMiaoshaPermission(MiaoshaUser user, long goodsId, String path, Integer verifyCode) {
        //校验秒杀地址是否正确
        String realPath = redisService.get(MiaoshaKey.miaoshaPath, user.getId() + "_" + goodsId, String.class);
        if (!realPath.equals(path)) {
            return Result.error(Const.MIAOSHA_PATH_ERROR);
        }
        //校验验证码对不读
        Integer realCode = redisService.get(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId, Integer.TYPE);
        if (verifyCode == null || verifyCode - realCode != 0) {
            return Result.error(Const.MIAOSHA_VERIFY_CODE_ERROR);
        }
        //删除redis中的结果
        redisService.delete(MiaoshaKey.getMiaoshaVerifyCode, user.getId() + "," + goodsId);

        //该方法返回的是减1后的数量
        long stock = redisService.decr(GoodsKey.goodsStock, "" + goodsId);
        boolean over = localMap.get(goodsId);
        if (over) {
            return Result.error(Const.MIAO_SHA_OVER);
        }
        if (stock < 0) {
            localMap.put(goodsId, true);
            return Result.error(Const.MIAO_SHA_OVER);
        }
        //   判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdAndGoodsId(user.getId(), goodsId);
        if (order != null) {
            return Result.error(Const.REPEATE_MIAOSHA);
        }
        return null;
    }

    public long getMiaoshaResult(MiaoshaUser user, long goodsId) {
        MiaoshaOrder miaoshaOrder = orderService.getMiaoshaOrderByUserIdAndGoodsId
                (user.getId(), goodsId);
        //如果秒杀成功
        if (miaoshaOrder != null && miaoshaOrder.getOrderId() != null) {
            return miaoshaOrder.getOrderId();
        }
        //失败或者排队中
        boolean isOver = getGoodsOver(goodsId);
        //如果失败了说明就卖完了
        if (isOver) {
            return -1;
        }
        //没有结果则说明是在排队
        return 0;
    }

    public Result<String> getMiaoshaPath(MiaoshaUser user, Long goodsId) {
        String str = MD5Util.md5(UUID.randomUUID().toString());
        redisService.set(MiaoshaKey.miaoshaPath, user.getId() + "_" + goodsId, str);
        return Result.success(str);
    }

    private void setGoodsOver(long goodsId) {
        redisService.set(MiaoshaKey.isGoodsOver, "" + goodsId, true);
    }

    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(MiaoshaKey.isGoodsOver, "" + goodsId);
    }


    /**
     * + - *生成随机数
     */
    private String generateVerifyCode(Random rdm) {
        char[] ops = new char[]{'+', '-', '*'};
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        return "" + num1 + op1 + num2 + op2 + num3;
    }

    /**
     * 计算表达式结果
     *
     * @param exp
     * @return
     */
    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer) engine.eval(exp);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
